package cn.dnui_yxk801.dnuifood_16110100801.controller;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.dnui_yxk801.dnuifood_16110100801.R;
import cn.dnui_yxk801.dnuifood_16110100801.bean.CollectBean;
import cn.dnui_yxk801.dnuifood_16110100801.bean.FoodBean;
import cn.dnui_yxk801.dnuifood_16110100801.bean.ResultBean;
import cn.dnui_yxk801.dnuifood_16110100801.listener.OnRetrofitListener;
import cn.dnui_yxk801.dnuifood_16110100801.model.FoodModel;
import cn.dnui_yxk801.dnuifood_16110100801.model.ShopModel;
import cn.dnui_yxk801.dnuifood_16110100801.model.UserModel;

import static android.view.View.GONE;
import static cn.dnui_yxk801.dnuifood_16110100801.MainActivity.userid;
import static cn.dnui_yxk801.dnuifood_16110100801.controller.LoginActivity.username;

public class FoodPurchaseActivity extends BaseActivity implements OnRetrofitListener,View.OnClickListener{
    private TextView tv_username;
    private TextView tv_shopname;
    private TextView tv_foodname;
    private TextView tv_price;
    private TextView tv_num;
    private TextView tv_sum;
    private TextView tv_time;
    private TextView tv_sum2;
    private EditText et_address;
    private ListView lv_address;
    private Button btn_submit;
    private Button btn_add;
    private Button btn_reduce;
    private String foodid;
    private String shopid;
    private String shopname;
    private Spinner time;
    //private Date date;
    private int num;
    private String num1;
    private int sum;
    private String sum1;
    private String address;
    private String suggesttime;
    private double price;
    private static final String CITY="大连";
    private boolean search_flag=false;
    private String selectedResult="";
    final String[] stime = new String[1];

    @Override
    void initViews() {
        layout_file=R.layout.activity_food_purchase;
        setLayout(layout_file);
        tv_username=findViewById(R.id.pc_tv_username1);
        tv_shopname=findViewById(R.id.pc_tv_shopname1);
        tv_foodname=findViewById(R.id.pc_tv_foodname);
        tv_price=findViewById(R.id.pc_tc_price);
        tv_num=findViewById(R.id.pc_tv_num);
        tv_sum=findViewById(R.id.pc_tv_sum);
        tv_sum2=findViewById(R.id.pc_tv_sum2);
        tv_time=findViewById(R.id.pc_tv_time);
        time=findViewById(R.id.pc_spinner);
        et_address=findViewById(R.id.pc_et_address);
        lv_address=findViewById(R.id.pc_lv_address);
        btn_submit=findViewById(R.id.pc_btn_submit);
        btn_add=findViewById(R.id.pc_btn_add);
        btn_reduce=findViewById(R.id.pc_btn_reduce);
        num=1;
        sum=1;
    }
//大连
    @Override
    void initEvents() {
        btn_submit.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        btn_reduce.setOnClickListener(this);
        et_address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str=et_address.getText().toString();
                if (!"".equals(str)&&search_flag){
                    if (!str.equals(selectedResult))
                        initMapLocationInfo(str,CITY);
                }else
                    lv_address.setVisibility(GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {
                search_flag=true;
            }
        });
        lv_address.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView=(TextView)view.findViewById(android.R.id.text1);
                selectedResult=textView.getText().toString();
                et_address.setText(selectedResult);
                search_flag=false;
                lv_address.setVisibility(GONE);
            }
        });
    }

    public void initMapLocationInfo(String keyWord,String cityCode){
        final int count;
        PoiSearch.Query query=new PoiSearch.Query(keyWord,null,cityCode);
        query.setPageSize(10);
        query.setPageNum(1);
        PoiSearch poiSearch=new PoiSearch(this,query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int rCode) {
                List<String>strs=new ArrayList();
                ArrayList<PoiItem>items=poiResult.getPois();
                if (items!=null&&items.size()>0){
                    PoiItem item=null;
                    for (int i=0,count=items.size();i<count;i++ ){
                        item=items.get(i);
                        strs.add(item.getTitle());
                    }
                    lv_address.setVisibility(View.VISIBLE);
                    ArrayAdapter<String>array=new ArrayAdapter(FoodPurchaseActivity.this,android.R.layout.simple_list_item_1,strs);
                    lv_address.setAdapter(array);
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }
    @Override
    public void onClick(View view) {
        if (view.getId()==R.id.pc_btn_add){
            num+=1;
            tv_num.setText(num+"份");
            sum=(int)price*num;
            tv_sum.setText("￥"+sum);
            tv_sum2.setText("￥"+sum);
        }
        if (view.getId()==R.id.pc_btn_reduce){
            if (num>0) {
                num -= 1;
                tv_num.setText(num + "份");
                sum=(int)price*num;
                tv_sum.setText("￥" + sum);
                tv_sum2.setText("￥" + sum);
            }
        }
        if (view.getId()==R.id.pc_btn_submit){
            num1=num+"";
            sum1=sum+"";
            suggesttime=stime[0];
            address=et_address.getText().toString();
            FoodModel foodModel=new FoodModel();
            foodModel.insertOrder(userid,foodid,num1,sum1,suggesttime,address,this);
        }


    }
    @Override
    void initDatas() {
        Date date=new Date();
        Intent intent=getIntent();
        foodid=intent.getStringExtra("foodid");
        shopid=intent.getStringExtra("shopid");
        shopname=intent.getStringExtra("shopname");
        FoodModel foodModel=new FoodModel();
        foodModel.getFoodById(foodid,this);
        tv_shopname.setText(shopname);
        setSpinner(time,date);



    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onSuccess(Object object, int flag) {
        if (flag==1){
            FoodBean foodBean=(FoodBean)object;
            tv_foodname.setText(foodBean.getFoodname());
            tv_username.setText(username);
            tv_price.setText("￥"+foodBean.getPrice());
            price=Double.parseDouble(foodBean.getPrice());
            sum=(int)price*num;
            tv_num.setText(num+"份");
            tv_sum.setText("￥"+sum);
            tv_sum2.setText("￥"+sum);
        }
        if (flag==5){
            ResultBean resultBean=(ResultBean)object;
            if (resultBean.getSuccess().equals("1")){
                Toast.makeText(FoodPurchaseActivity.this,"购买成功",Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(FoodPurchaseActivity.this,FoodListActivity.class);
                intent.putExtra("shopid",shopid);
                intent.putExtra("shopname",shopname);
                startActivity(intent);
            }
            else {
                Toast.makeText(FoodPurchaseActivity.this,"购买失败",Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(FoodPurchaseActivity.this,FoodListActivity.class);
                intent.putExtra("shopid",shopid);
                intent.putExtra("shopname",shopname);
                startActivity(intent);
            }
        }

    }



    @Override
    public void onFalure(String msg) {

    }





    public void setSpinner(Spinner sp,Date date){

        Date []dates=new Date[5];
        for (int i=0;i<dates.length;i++){
            dates[i]=new Date(date.getTime()+(long)30*60*1000*(i+1)+(long)8*60*60*1000*(1));
        }
        final String[] mItems=new String[dates.length-1];
        for (int i=0;i<mItems.length;i++){
            mItems[i]=dates[i].getHours()+":"+formateMinute(dates[i].getMinutes())+"----"+dates[i+1].getHours()+":"+formateMinute(dates[i+1].getMinutes());
        }
        ArrayAdapter<String>adapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,mItems);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {

                stime[0] =mItems[pos];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
    public String formateMinute(int minute){
        if (minute<10)
            return "0"+minute;
        else
            return minute+"";
    }
}
